package cn.tedu.sp06.fb;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class OrderFB implements FallbackProvider {
    //    针对哪个模块，应用当前降级类
//    item-service： 只对商品降级
//    * ：  对所有模块都应用当前降级类
//    null : 对所有模块都应用当前降级类
    @Override
    public String getRoute() {
        return "order-service";
    }

    //发送给客户端的降级响应
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            //            返回HttpStatus对象 封装了状态码和状态文本
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            //状态码
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }

            //状态文本
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
            }

            @Override
            public void close() {
//用来关闭输入流，释放系统资源
//                ByteArrayInputStream 只封装虚拟机中的内存数组，不占用系统的底层资源
            }

            @Override
            public InputStream getBody() throws IOException {
//                josnresult -- > {code:500,msg:服务失败,data : null}
                String s = JsonResult.build().code(500).msg("调用后台服务失败").toString();
//                返回的 协议提数据ByteArrayInputStream（数组 （s转换为数组））
                return new ByteArrayInputStream(s.getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders h = new HttpHeaders();
                h.set("Content-Type", "application/json;charset=UTF-8");
                return h;
            }
        };
    }
}
